﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Trinity.Core;
using System.Threading.Tasks;

namespace TrinitySequenceAssembly
{
    class KmerCreateRequest
    {
        private int m_SlaveID;
        private List<DebruijnNode> m_DebruijnNodeList;

        public int SlaveID
        {
            get { return m_SlaveID; }
        }

        public KmerCreateRequest()
        {
        }

        public KmerCreateRequest(int slaveID, List<DebruijnNode> debruijnNodeList)
        {
            m_SlaveID = slaveID;
            m_DebruijnNodeList = debruijnNodeList;
        }
    }

    class KmerCreateRequestService
    {
        private List<DebruijnNode> m_AllNodeList;
        public KmerCreateRequestService(List<DebruijnNode> allNodeList)
        {
            m_AllNodeList = allNodeList;
        }

        private static int GetLocatedSlaveID(long cid)
        {
            return BitConverter.GetBytes(cid)[1] % Global.SlaveCount;
        } 

        private Dictionary<int, List<DebruijnNode>> GetRequestTable()
        {
            Dictionary<int, List<DebruijnNode>> table = new Dictionary<int, List<DebruijnNode>>();
            foreach (DebruijnNode dn in m_AllNodeList)
            {
                int slaveID = GetLocatedSlaveID(dn.CompressedKmer);
                List<DebruijnNode> th = null;
                if (table.TryGetValue(slaveID, out th) == true)
                {
                    th.Add(dn);
                }
                else
                {
                    th = new List<DebruijnNode>();
                    th.Add(dn);
                    table.Add(slaveID, th);
                }
            }
            return table;
        }

        public List<KmerCreateRequest> GetRequestList()
        {
            List<KmerCreateRequest> res = new List<KmerCreateRequest>();
            Dictionary<int, List<DebruijnNode>> requestTable = GetRequestTable();
            foreach(KeyValuePair<int, List<DebruijnNode>> kv in requestTable)
            {
                KmerCreateRequest kcr = new KmerCreateRequest(kv.Key, kv.Value);
                res.Add(kcr);
            }
            return res;
        }
    }
    class KmerCreator
    {
        public static void CreateDebruijnCell(List<DebruijnNode> debruijnNodeList)
        {
            KmerCreateRequestService kcrs = new KmerCreateRequestService(debruijnNodeList);
            List<KmerCreateRequest> requestList = kcrs.GetRequestList();
            Parallel.For(0, requestList.Count, i =>
            {
                try
                {
                    
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                }
            });
        }
    }
}
